<template>
  <codemirror ref="codemirror" :height="getHeight" :options="cmOptions" :value="modelValue" @changes="changes" />
</template>

<script>
  import { defineComponent } from 'vue'
  import codemirror from 'codemirror-editor-vue3'
  // plugin-style
  import 'codemirror-editor-vue3/dist/style.css'
  // language
  import 'codemirror/mode/sql/sql.js'
  import 'codemirror/mode/javascript/javascript.js'
  import 'codemirror/addon/display/autorefresh.js'
  // theme
  import 'codemirror/theme/dracula.css'
  //代码折叠
  import 'codemirror/addon/fold/foldgutter.css'
  import 'codemirror/addon/fold/foldcode'
  import 'codemirror/addon/fold/foldgutter'
  import 'codemirror/addon/fold/brace-fold'
  import 'codemirror/addon/fold/comment-fold'
  import isNumber from 'lodash/isNumber'
  export default defineComponent({
    name: 'CodeEditor',
    components: {
      codemirror,
    },
    props: {
      modelValue: {
        type: String,
        default: '',
      },
      name: {
        type: String,
        default: function () {
          return ''
        },
      },
      height: {
        type: [Boolean, Number],
        default: false,
      },
      cmOptions: {
        type: Object,
        default: () => {
          return {
            tabSize: 1,
            smartIndent: true,
            indetUnit: 1,
            styleActiveLine: true,
            lineNumbers: true,
            line: true,
            mode: 'text/x-mysql',
            theme: 'dracula',
            foldGutter: true,
            lineWrapping: true,
            autoRefresh: true,
            // mode: 'text/javascript',
          }
        },
      },
    },
    emits: ['update:modelValue'],
    data() {
      return {}
    },
    computed: {
      getHeight() {
        let open = ''
        if (this.height === true) {
          open = '100%'
        }
        if (isNumber(this.height)) {
          open = this.height
        }
        if (this.height === false) {
          open = 200
        }
        console.log('getHeight', this.height, open)
        return open
      },
    },
    watch: {},
    mounted() {
      this.refresh()
    },
    methods: {
      changes(newCode) {
        this.$emit('update:modelValue', newCode.getValue())
      },
      refresh() {
        setTimeout(() => {
          this.$refs.codemirror.cminstance.refresh()
        }, 1000)
      },
    },
  })
</script>
<style lang="scss">
  .CodeMirror-line span {
    // padding: 0 5px 0 5px;
    padding: 0;
    font-size: 20px;
    margin-left: 0 !important;
  }
  .cm-s-dracula span.cm-comment {
    margin-left: 0;
    padding-left: 0;
  }
  .CodeMirror-wrap {
    width: 100% !important;
  }
</style>
